package com.xmkj.bearbiz.member;

import android.graphics.Color;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.BearBean.MemberListBean;
import com.common.BearMethods.GetMemberListInfoMethods;
import com.common.adapter.helper.IRecyclerViewHelper;
import com.common.cons.Constans;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.utils.EmptyUtils;
import com.common.utils.SPUtils;
import com.common.utils.SizeUtils;
import com.common.widget.DividerDecoration.MarginDecoration;
import com.common.widget.constumpop.CustomPopWindow;
import com.common.widget.recyclerview.refresh.recycleview.XRecyclerView;
import com.xmkj.bearbiz.R;
import com.xmkj.bearbiz.utils.BottomPickerUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Create by leo
 * 创建日期：2018/6/14
 * 描述：
 */

public class SearchAndMemberListActivity extends BaseMvpActivity {
    public static final String TYPE = "type";
    public static final String CLIENTCODE = "CLIENTCODE";
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_menber_title)
    TextView tvMenberTitle;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.et_content)
    EditText etSearh;
    @BindView(R.id.rl_search)
    RelativeLayout rlSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.tv_data_sort)
    CheckedTextView tvDataSort;
    @BindView(R.id.tv_filter)
    CheckedTextView tvFilter;
    @BindView(R.id.recyclerview)
    XRecyclerView recyclerview;
  /*  @BindView(R.id.fragment_container)
    FrameLayout fragmentContainer;*/
    @BindView(R.id.drawer_content)
    RelativeLayout drawerContent;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    List<MemberListBean.ListsEntity> bean = new ArrayList<>();
    @BindView(R.id.et_age_start)
    EditText etAgeStart;
    @BindView(R.id.et_age_end)
    EditText etAgeEnd;
    @BindView(R.id.tv_date_start)
    TextView tvDateStart;
    @BindView(R.id.tv_date_end)
    TextView tvDateEnd;
    @BindView(R.id.tv_comstum_date)
    TextView tvComstumBegin;
    @BindView(R.id.tv_end_date)
    TextView tvComstumEnd;
    @BindView(R.id.et_money_start)
    EditText etMoneyStart;
    @BindView(R.id.et_money_end)
    EditText etMoneyEnd;
    @BindView(R.id.et_time_start)
    EditText etTimeStart;
    @BindView(R.id.et_time_end)
    EditText etTimeEnd;
    @BindView(R.id.et_jifen_start)
    EditText etJifenStart;
    @BindView(R.id.et_jifen_end)
    EditText etJifenEnd;
    @BindView(R.id.et_guwen)
    EditText etGuwen;
    @BindView(R.id.et_day_start)
    EditText etDayStart;
    @BindView(R.id.et_day_end)
    EditText etDayEnd;
    @BindView(R.id.tv_reset)
    TextView tvReset;
    @BindView(R.id.tv_true)
    TextView tvTrue;
    @BindView(R.id.tv_count)
    TextView tv_count;
    private MemberListAdapter adapter;
    private CustomPopWindow mCustomPopWindow;
    private String clientcode = "";
    private String type;
    private  int timeType  ;
    private int windowsWight;
    private int windowsHeight;

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_memberlist;
    }

    @Override
    protected void onViewCreated() {

    }

    @Override
    protected void doLogicFunc() {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        windowsWight = metric.widthPixels;
        windowsHeight = metric.heightPixels;
        ViewGroup.LayoutParams leftParams = drawerContent.getLayoutParams();
        leftParams.height = windowsHeight;
        leftParams.width = windowsWight;
        drawerContent.setLayoutParams(leftParams);
        type = getIntent().getStringExtra(TYPE); // type : 1  搜索进来的
        clientcode = getIntent().getStringExtra(CLIENTCODE);

        if(type.equals("1")){
            rlSearch.setVisibility(View.VISIBLE);
            tvSearch.setVisibility(View.VISIBLE);
            tvMenberTitle.setVisibility(View.GONE);
        }else {
            rlSearch.setVisibility(View.GONE);
            tvSearch.setVisibility(View.GONE);
            tvMenberTitle.setVisibility(View.VISIBLE);
        }
        attachClickListener(tvFilter);
        gotoHttpRep();
        setRecyclerView();
        initDrawbleLisner();
        attachClickListener(tvDataSort);
        attachClickListener(tvDateStart);
        attachClickListener(tvDateEnd);
        attachClickListener(tvComstumBegin);
        attachClickListener(tvComstumEnd);
        attachClickListener(tvTrue);
        attachClickListener(tvReset);
        attachClickListener(ivBack);
        attachClickListener(tvSearch);


    }

    @Override
    protected void onViewClicked(View view) {
        if (view.getId() == tvFilter.getId()) {
            drawerLayout.openDrawer(drawerContent);
        } else if (view.getId() == tvDataSort.getId()) {
            if (isDataSortChecked) {  // 已经被选中了  升序状态
                tvDataSort.setChecked(false);
                tvFilter.setChecked(false);
                isDataSortChecked = false;

                // 处理pop
            } else {
                tvFilter.setChecked(false);
                tvDataSort.setChecked(true);
                isDataSortChecked = true;
                //      弹出pop
                showPop();
            }
        } else if (tvDateStart.getId() == view.getId()) { //  注册开始时间
            timeType = 1 ;
            Calendar startTime = Calendar.getInstance();
            int year = startTime.get(Calendar.YEAR);    //获取年
            int month = startTime.get(Calendar.MONTH);   //获取月份，0表示1月份
            int day = startTime.get(Calendar.DAY_OF_MONTH);    //获取当前天数
            startTime.set(year, month, day);
            Calendar endTime = Calendar.getInstance();
            endTime.set(2099, 0, 1);
            Calendar selectTime = Calendar.getInstance();
            MyDatePickerRepaymentDate myDatePickerCallBack = new MyDatePickerRepaymentDate();
            BottomPickerUtils.showDatePicker(context, endTime, startTime, selectTime, myDatePickerCallBack);
        } else if (tvDateEnd.getId() == view.getId()) {   // 注册结束时间
            timeType = 2 ;
            Calendar startTime = Calendar.getInstance();
            int year = startTime.get(Calendar.YEAR);    //获取年
            int month = startTime.get(Calendar.MONTH);   //获取月份，0表示1月份
            int day = startTime.get(Calendar.DAY_OF_MONTH);    //获取当前天数
            startTime.set(year, month, day);
            Calendar endTime = Calendar.getInstance();
            endTime.set(2099, 0, 1);
            Calendar selectTime = Calendar.getInstance();
            MyDatePickerRepaymentDate myDatePickerCallBack = new MyDatePickerRepaymentDate();
            BottomPickerUtils.showDatePicker(context, endTime, startTime, selectTime, myDatePickerCallBack);
        } else if (tvComstumBegin.getId() == view.getId())  {   // 消费开始时间
            timeType = 3 ;
            Calendar startTime = Calendar.getInstance();
            int year = startTime.get(Calendar.YEAR);    //获取年
            int month = startTime.get(Calendar.MONTH);   //获取月份，0表示1月份
            int day = startTime.get(Calendar.DAY_OF_MONTH);    //获取当前天数
            startTime.set(year, month, day);
            Calendar endTime = Calendar.getInstance();
            endTime.set(2099, 0, 1);
            Calendar selectTime = Calendar.getInstance();
            MyDatePickerRepaymentDate myDatePickerCallBack = new MyDatePickerRepaymentDate();
            BottomPickerUtils.showDatePicker(context, endTime, startTime, selectTime, myDatePickerCallBack);
        } else if (tvComstumEnd.getId() == view.getId()) { // 消费结束时间
            timeType = 4 ;
            Calendar startTime = Calendar.getInstance();
            int year = startTime.get(Calendar.YEAR);    //获取年
            int month = startTime.get(Calendar.MONTH);   //获取月份，0表示1月份
            int day = startTime.get(Calendar.DAY_OF_MONTH);    //获取当前天数
            startTime.set(year, month, day);
            Calendar endTime = Calendar.getInstance();
            endTime.set(2099, 0, 1);
            Calendar selectTime = Calendar.getInstance();
            MyDatePickerRepaymentDate myDatePickerCallBack = new MyDatePickerRepaymentDate();
            BottomPickerUtils.showDatePicker(context, endTime, startTime, selectTime, myDatePickerCallBack);
        }else if(tvTrue.getId()==view.getId()){
            mPageIndex = 1 ;
            // drawlayout 弹出
            drawerLayout.closeDrawer(drawerContent);

            gotoHttpRep();

        }else if(tvReset.getId()==view.getId()){
            // 重置
            resetView(etAgeEnd,etAgeStart,tvDateStart,tvDateEnd,tvComstumBegin,tvComstumEnd,etMoneyStart,etMoneyEnd,etTimeStart,etTimeEnd
            ,etJifenStart,etJifenEnd,etGuwen,etDayStart,etDayEnd);

        }else if(ivBack.getId()==view.getId()){
            onBackPressed();
        } else if(tvSearch.getId()==view.getId()){
            mPageIndex = 1 ;
            // drawlayout 弹出

            gotoHttpRep();
        }
    }
    private void resetView(TextView... views){
        for (int i = 0; i < views.length; i++) {
            TextView f =  views[i];
            f.setText("");
        }
    }
    private class MyDatePickerRepaymentDate implements BottomPickerUtils.DatePickerCallback {

        @Override
        public void onDateSelect(Calendar calendar) {
            int year = calendar.get(Calendar.YEAR);    //获取年
            int month = calendar.get(Calendar.MONTH) + 1;   //获取月份，0表示1月份
            int day = calendar.get(Calendar.DAY_OF_MONTH);    //获取当前天数
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int min = calendar.get(Calendar.MINUTE);
            String time = year + "-" + month + "-" + day;
          switch (timeType){
              case 1:
                  tvDateStart.setText(time);
                  break;
              case 2:
                  tvDateEnd.setText(time);
                  break;
              case 3:
                  tvComstumBegin.setText(time);
                  break;
              case 4:
                  tvComstumEnd.setText(time);
                  break;
          }
            System.out.println(year + "----------" + month + "月" + day + "日" + hour + "时" + min + "分钟");
//            tvTime.setText(year + "年" + month + "月" + day + "日" + hour + "时" + min + "分");
//            sendtime = calendar.getTimeInMillis() / 1000 + "";
//            has_choose_time = true;
//            end_time = year+"."+month+"."+day;
        }
    }
    private void initDrawbleLisner() {
        drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            /**
             * 当抽屉滑动状态改变的时候被调用
             * 状态值是STATE_IDLE（闲置--0）, STATE_DRAGGING（拖拽的--1）, STATE_SETTLING（固定--2）中之一。
             * 抽屉打开的时候，点击抽屉，drawer的状态就会变成STATE_DRAGGING，然后变成STATE_IDLE
             */
            @Override
            public void onDrawerStateChanged(int arg0) {
                Log.i("drawer", "drawer的状态：" + arg0);
            }

            /**
             * 当抽屉被滑动的时候调用此方法
             * arg1 表示 滑动的幅度（0-1）
             */
            @Override
            public void onDrawerSlide(View arg0, float arg1) {
                Log.i("drawer", arg1 + "");
            }

            /**
             * 当一个抽屉被完全打开的时候被调用
             */
            @Override
            public void onDrawerOpened(View arg0) {
                Log.i("drawer", "抽屉被完全打开了！");
                tvFilter.setChecked(true);
                tvDataSort.setChecked(false);
            }

            /**
             * 当一个抽屉完全关闭的时候调用此方法
             */
            @Override
            public void onDrawerClosed(View arg0) {
                Log.i("drawer", "抽屉被完全关闭了！");
                tvFilter.setChecked(false);

            }
        });
    }

    private void setRecyclerView() {
//        IRecyclerViewHelper.init().setRecycleLineLayout(context, LinearLayoutManager.VERTICAL, recyclerview);
       /* GridLayoutManager layoutManager = new GridLayoutManager(context, 2);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);*/
        IRecyclerViewHelper.init().setRecycleLineLayout(context, LinearLayoutManager.VERTICAL, recyclerview);
        recyclerview.addItemDecoration(new MarginDecoration(LinearLayoutManager.VERTICAL, (int) SizeUtils.dp2px(context, 1)));
        recyclerview.setHasFixedSize(true);
        recyclerview.setRefreshing(false);
//        recyclerview.addItemDecoration(new MarginDecoration(LinearLayoutManager.HORIZONTAL, (int) SizeUtils.dp2px(context, 1)));
//        recyclerview.addItemDecoration(new MarginDecoration(LinearLayoutManager.VERTICAL, (int) SizeUtils.dp2px(context, 1)));
        recyclerview.setLoadMoreEnabled(true);
        adapter = new MemberListAdapter(context, bean ,clientcode);
//        adapter.setOnItemClickSeclect(this);
        recyclerview.setAdapter(adapter);
        recyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mPageIndex = 1;
                mIsRefreshOrLoadMore = 0;
                gotoHttpRep();
            }

            @Override
            public void onLoadMore() {
                if (mIsHasNoData) {
                    recyclerview.loadMoreComplete();
                    recyclerview.setNoMore(true);
                    return;
                }
                mPageIndex++;
                mIsRefreshOrLoadMore = 1;
                gotoHttpRep();
            }
        });
    }


    private void gotoHttpRep() {
        if(type.equals("1")){  // 搜索进来的
            clientcode = "";
            search = getEditTextStr(etSearh);
        } else { //店铺进来的
            search = "";
        }
        if(EmptyUtils.isNotEmpty(getEditTextStr(etAgeStart))&&EmptyUtils.isNotEmpty(getEditTextStr(etAgeEnd))){
            screen_age = getEditTextStr(etAgeStart)+"/"+getEditTextStr(etAgeEnd);
        }
        if(EmptyUtils.isNotEmpty(tvDateStart.getText().toString())&&EmptyUtils.isNotEmpty(tvDateEnd.getText().toString())){
            screen_registdate = tvDateStart.getText().toString()+"/"+tvDateEnd.getText().toString();
        }
        if(EmptyUtils.isNotEmpty(tvComstumBegin.getText().toString())&&EmptyUtils.isNotEmpty(tvComstumEnd.getText().toString())){
            screen_paydate = tvComstumBegin.getText().toString()+"/"+tvComstumEnd.getText().toString();
        }
        if(EmptyUtils.isNotEmpty(getEditTextStr(etMoneyStart))&&EmptyUtils.isNotEmpty(getEditTextStr(etMoneyEnd))){
            screen_money = getEditTextStr(etMoneyStart)+"/"+getEditTextStr(etMoneyEnd);
        }
        if(EmptyUtils.isNotEmpty(getEditTextStr(etTimeStart))&&EmptyUtils.isNotEmpty(getEditTextStr(etTimeEnd))){
            screen_paynum = getEditTextStr(etTimeStart)+"/"+getEditTextStr(etTimeStart);
        }
        if(EmptyUtils.isNotEmpty(getEditTextStr(etJifenStart))&&EmptyUtils.isNotEmpty(getEditTextStr(etJifenEnd))){
            screen_score = getEditTextStr(etTimeStart)+"/"+getEditTextStr(etTimeStart);
        }
        screen_consultant = getEditTextStr(etGuwen);
        if(EmptyUtils.isNotEmpty(getEditTextStr(etDayStart))&&EmptyUtils.isNotEmpty(getEditTextStr(etDayEnd))){
            screen_notpayday = getEditTextStr(etDayStart)+"/"+getEditTextStr(etDayEnd);
        }
        CommonSubscriber<MemberListBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                MemberListBean beans = (MemberListBean) o;

                SpannableString spannableString = new SpannableString("搜索会员数量："+""+beans.total+"人");
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FF0E41")), 7,spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv_count.setText(spannableString);

                List<MemberListBean.ListsEntity> beanList = beans.lists;
                recyclerview.loadMoreComplete();
                // 下拉刷新
                if (mIsRefreshOrLoadMore == 0) {
                    recyclerview.refreshComplete();
                    adapter.clear();
                }

                if (EmptyUtils.isNotEmpty(beanList)) {
                    bean = beanList;
                    adapter.addAll(bean);
                } else if (mIsRefreshOrLoadMore == 0) {
//                    statusEmpty();
                    return;
                }

                if (EmptyUtils.isEmpty(beanList)) {
                    recyclerview.setNoMore(true);
                } else {
                    mIsHasNoData = beanList.size() < mPageSize;
                    recyclerview.setNoMore(mIsHasNoData);
                }
                adapter.notifyDataSetChanged();
                recyclerview.refreshComplete();
                recyclerview.loadMoreComplete();
                if (mIsRefreshOrLoadMore == 0) {
                    dismissProgressDialog();
                }
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();

                SpannableString spannableString = new SpannableString("搜索会员数量："+""+0+"人");
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FF0E41")), 7,spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv_count.setText(spannableString);
                adapter.clear();
                showToastMsg(e);
                adapter.notifyDataSetChanged();
                recyclerview.refreshComplete();
                recyclerview.loadMoreComplete();
                if (mIsRefreshOrLoadMore == 0) {
                    dismissProgressDialog();
                }
            }
        });


        GetMemberListInfoMethods.getInstance().viplist(subscriber, SPUtils.getShareInt(Constans.UID) + "", SPUtils.getShareString(Constans.HASHID), mPageIndex,
                clientcode,
                search,
                sort_type,
                screen_age,
                screen_registdate,
                screen_paydate,
                screen_money,
                screen_paynum,
                screen_score,
                screen_consultant,
                screen_notpayday
        );
        rxManager.add(subscriber);
    }

    String search = "";
    String sort_type = "";
    String screen_age = "";
    String screen_registdate = "";
    String screen_paydate = "";
    String screen_money = "";
    String screen_paynum = "";
    String screen_consultant = "";
    String screen_notpayday = "";
    String screen_score = "";
    private boolean isDataSortChecked = false;


    private void showPop() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_menu, null);
        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
//                .enableOutsideTouchableDissmiss(false)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAsDropDown(tvDataSort, 0, 10);
    }

    private void handleLogic(View contentView) {

        RadioGroup rg = contentView.findViewById(R.id.radio_group);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                mCustomPopWindow.dissmiss();
                tvDataSort.setChecked(true);
                tvFilter.setChecked(false);
                isDataSortChecked = false;

                switch (checkedId) {
                    case R.id.rb_jifen:
                        sort_type = "1";
                        gotoHttpRep();
                        tvDataSort.setText("积分");
                        break;
                    case R.id.rb_register_time:
                        sort_type = "2";
                        gotoHttpRep();
                        tvDataSort.setText("注册时间");
                        break;
                    case R.id.rb_kaika_date:
                        sort_type = "3";
                        gotoHttpRep();
                        tvDataSort.setText("开卡日期");
                        break;
                    case R.id.rb_comstum_date:
                        sort_type = "4";
                        gotoHttpRep();
                        tvDataSort.setText("消费日期");
                        break;
                    case R.id.rb_huifang_date:
                        sort_type = "5";
                        gotoHttpRep();
                        tvDataSort.setText("回访日期");
                        break;
                    case R.id.rb_comstum_time:
                        sort_type = "6";
                        gotoHttpRep();
                        tvDataSort.setText("消费次数");
                        break;
                    case R.id.rb_all_money:
                        sort_type = "7";
                        gotoHttpRep();
                        tvDataSort.setText("总消费额");
                        break;

                }
            }
        });
        /*
        contentView.findViewById(R.id.rb_register_time).setOnClickListener(listener);
        contentView.findViewById(R.id.rb_kaika_date).setOnClickListener(listener);
        contentView.findViewById(R.id.rb_comstum_date).setOnClickListener(listener);
        contentView.findViewById(R.id.rb_huifang_date).setOnClickListener(listener);
        contentView.findViewById(R.id.rb_comstum_time).setOnClickListener(listener);
        contentView.findViewById(R.id.rb_all_money).setOnClickListener(listener);*/
    }

    @Override
    public void bindKnife() {
        ButterKnife.bind(this);
    }


}
